const Db = require("../utils/db");
const createSql = require("../utils/Create_SQL");
const utils = require('../utils/utils.js');
const $errorCode = require('../config/config').errorCode;

async function setLog(req, res) {
    let method = req.method.toLowerCase();
    if (method == 'options') return;
    let resData = {};
    resData = method == 'get' ? req.query : req.body;
    let pass = utils.detectSQL(resData);
    if (!pass) return
    if (resData.token) delete resData.token;
    let userInfo = {};
    try {
        userInfo = await utils.isLogin(req, res, false);
        userInfo = userInfo.data;
    } catch (error) {
        userInfo = {};
    }
    let updateLog = {
        ID: utils.getUuid(),
        requestUrl: req.originalUrl.split('?')[0],
        ip: utils.getClientIP(req),
        options: method,
        query: "",
        createdTime: utils.getTime(),
        userInfo: JSON.stringify(userInfo) || null,
        creareByUser: userInfo?.ID || null,
        username: userInfo?.username || null,
        status: res.statusCode
    }
    let insetData = {}
    // 取得ip前两位
    let ip = utils.getClientIP(req).split('.');
    insetData.ipFirst = ip[0] + '.' + ip[1];
    let hasIpSql = createSql.select().from('iplocation').where(`ip = '${utils.getClientIP(req)}'`).build();
    let hasIp = await Db.query(hasIpSql, res);
    if (hasIp.length < 0) {
        let hasFirstSql = createSql.select().from('iplocation').where(`ipFirst = '${insetData.ipFirst}'`).build();
        let hasFirst = await Db.query(hasFirstSql);
        if (hasFirst.length > 0) {
            console.log("hasFirst");
            insetData = hasFirst[0];
            insetData.ip = utils.getClientIP(req);
            insetData.ID = utils.getUuid();
            insetData.createdTime = utils.getTime();
            await Db.query(createSql.insert('iplocation').value(insetData).build(), res);
            return;
        }
        let ipLocation = await utils.getIPByLocation(utils.getClientIP(req));
        let ipdata = ipLocation.ipdata;
        insetData.ip = utils.getClientIP(req);
        insetData.province = ipdata.info1;
        insetData.city = ipdata.info2;
        insetData.district = ipdata.info3;
        insetData.isp = ipdata.isp;
        insetData.ID = utils.getUuid();
        insetData.createdTime = utils.getTime();
        await Db.query(createSql.insert('iplocation').value(insetData).build(), res)
    }


    if (JSON.stringify(resData) != '{}') {
        updateLog.query = JSON.stringify(resData).length > 256 ? JSON.stringify(resData).substring(0, 256) + "..." : JSON.stringify(resData);
    }
    let sql = createSql.insert("actionLog").value(updateLog).build();
    Db.query(sql);
}

module.exports = setLog;